/**
 * Created by liuqingxia on 2016/3/14.
 */

var readerOrWriterTypeHasDataSource = ["drds", "mysql", "oracle","sqlserver"];//有相关数据源的reader或者Writer类型
var currentReaderDataSourceId;//当前选中的readerDataSource的id
var currentWriterDataSourceId;//当前选中的writerDataSource的id

/**
 * jobDataSource相关的方法
 */
function jobDataSourceRelevantFunctionsAndEvents() {

    /*默认显示drds数据源*/
    showOneTypeDataSource("reader-datasource-treeview", "drds", readerDataSourceButtons);
    showOneTypeDataSource("writer-datasource-treeview", "drds", writerDataSourceButtons);

    registerClickDataSourceUseButtonEvent("reader");
    registerClickDataSourceUseButtonEvent("writer");

    registerTableNameSelectChangeEvent("reader");
    registerTableNameSelectChangeEvent("writer");

    registerClickSelectAllColumnsBtnEvent("reader");
    registerClickSelectAllColumnsBtnEvent("writer");

    registerClickGiveUpAllColumnsBtnEvent("reader");
    registerClickGiveUpAllColumnsBtnEvent("writer");

    registerClickTableNameLiEvent("reader");
    registerClickTableNameLiEvent("writer");
}

/**
 * 判断一个reader或者writer,
 * 是否有数据源
 * @param type
 * @returns {boolean}
 */
function haveDataSource(type) {
    return readerOrWriterTypeHasDataSource.indexOf(type) != -1;
}

/**
 * 注册点击数据源列表的"使用"按钮事件
 */
function registerClickDataSourceUseButtonEvent(readerOrWriter) {
    $(document).on("click", "." + readerOrWriter + "Source-use-btn", function () {

        var dataSource = getCurrentDataSource($(this));
        var formId;
        var dataSourceId;

        if (readerOrWriter == "reader") {
            formId = readerFormId;
            currentReaderDataSourceId = $.trim(dataSource['id']);
            dataSourceId = currentReaderDataSourceId;
        } else {
            formId = writerFormId;
            currentWriterDataSourceId = $.trim(dataSource['id']);
            dataSourceId = currentWriterDataSourceId;
        }

        fillReaderOrWriterForm(dataSource, formId);

        fillReaderOrWriterTableSelect(dataSourceId, readerOrWriter);

        showColumnsCheckBoxByType(readerOrWriter);
    });
}

/**
 * 注册readerTable的select框的改变事件
 */
function registerTableNameSelectChangeEvent(readerOrWriter) {
    $(document).on("change", "#" + readerOrWriter + "-table-select", function () {
        showColumnsCheckBoxByType(readerOrWriter);
    });
}

/**
 * 注册点击列的CheckBox"全选"按钮
 */
function registerClickSelectAllColumnsBtnEvent(readerOrWriter) {
    $(document).on("click", "." + readerOrWriter + "-tableColumns-checkBox-selectAll-btn", function () {
        $.each($("." + readerOrWriter + "-tableColumn-checkBox"), function () {
            this.checked = true;
        });
    });
}

/**
 * 注册点击列的CheckBox"全不选"按钮
 */
function registerClickGiveUpAllColumnsBtnEvent(readerOrWriter) {
    $(document).on("click", "." + readerOrWriter + "-tableColumns-checkBox-GiveUpAll-btn", function () {
        $.each($("." + readerOrWriter + "-tableColumn-checkBox"), function () {
            this.checked = false;
        });
    });
}

/**
 * 显示当前table的columns
 * @param readerOrWriter
 */
function showColumnsCheckBoxByType(readerOrWriter) {
    var tableName = $("#" + readerOrWriter + "-table-select").val();
    var id;
    if (readerOrWriter == "reader") {
        id = currentReaderDataSourceId;
    } else {
        id = currentWriterDataSourceId;
    }
    var tableColumnArr = getTableColumns(id, $.trim(tableName));
    showColumnsCheckBox(tableColumnArr, readerOrWriter);
}

// /**
//  * 显示当前table的columns
//  * @param readerOrWriter
//  */
// function showColumnCheckBoxByType(direction) {
//     var tableNameSelect = $("#" + direction + "-table-select").val();
//     var id;
//     if (direction == "reader") {
//         id = currentReaderDataSourceId;
//     } else {
//         id = currentWriterDataSourceId;
//     }
//     var tableColumnArr = getTableColumns(id, $.trim(tableName));
//     showColumnsCheckBox(tableColumnArr, readerOrWriter);
// }

/**
 * 根据dataSource的id，tableName,
 * 获取表中的所有列名
 * @param id
 * @param tableName
 * @returns {Array}
 */
function getTableColumns(id, tableName) {

    var tableColumnArr = [];
    var params = {};
    params['id'] = id;
    params['tableName'] = $.trim(tableName);

    $.postHttpSync(params, getUrlBySuffix("/getTableColumns"), function (json) {
        if (json && json.success) {
            tableColumnArr = json['list'];
        }
    })
    return tableColumnArr;
}

/**
 * 显示tableColumns的checkBox区域
 * @param tableColumnArr
 * @param readerOrWriter
 */
function showColumnsCheckBox(tableColumnArr, readerOrWriter) {

    var tableColumnsCheckBoxRow = $("#" + readerOrWriter + "-tableColumns-checkBox-row");
    tableColumnsCheckBoxRow.empty();

    var checkBoxHtml = "";
    if (readerOrWriter == "reader") {
        checkBoxHtml += readerTableColumnsButtons;
    } else {
        checkBoxHtml += writerTableColumnsButtons;
    }

    for (var index in tableColumnArr) {

        var tableColumn = tableColumnArr[index];

        checkBoxHtml += "<label class='tableColumnsCheckbox'>" +
            "<input type='checkbox' " +
            "class='" + readerOrWriter + "-tableColumn-checkBox' " +
            "value='" + tableColumn + "'>" + tableColumn +
            "</label>";

    }

    tableColumnsCheckBoxRow.append(checkBoxHtml);

    showTableColumnsCheckBoxDiv(readerOrWriter);
}

/**
 * tableColumnsCheckBoxDiv隐藏
 * @param readerOrWriter
 */
function hideTableColumnsCheckBoxDiv(readerOrWriter) {
    $("#" + readerOrWriter + "-tableColumns-checkBox-div").hide();
}

/**
 * tableColumnsCheckBoxDiv显示
 * @param readerOrWriter
 */
function showTableColumnsCheckBoxDiv(readerOrWriter) {
    $("#" + readerOrWriter + "-tableColumns-checkBox-div").show();
}

/**
 * 根据dataSource的Id，将所有的table查询出来，
 * 并填充到table的select框
 * @param id
 */
function fillReaderOrWriterTableSelect(id, readerOrWriter) {
    var tableArr = getTableArrByDataSourceId(id);
    addOptionsToTableSelect(tableArr, readerOrWriter);
}

/**
 * 根据tableName数组，生成tableName的select
 * @param tableArr
 */
function addOptionsToTableSelect(tableArr, readerOrWriter) {

    var tableSelectRow = readerOrWriter + "-table-select-row";
    var selectRow = $("#" + tableSelectRow);
    selectRow.empty();

    var tableNameOptions = "";

    for (var index in tableArr) {

        var tableName = tableArr[index];

        tableNameOptions += "" +
            "<option value='" + tableName + "'>" +
            tableName +
            "</option>";
    }

    var tableNameSelect = "" +
        "<select class='selectpicker bs-select-hidden' style='width: 400px'" +
        "id='" + readerOrWriter + "-table-select'> " +
        tableNameOptions +
        "</select>";


    selectRow.append(tableNameSelect);
    selectRow.append(generateVisualTableNameSelectEle(tableArr, readerOrWriter));

    $("#" + readerOrWriter + "-table-select-div").show();
}

/**
 * 返回可视化的tableName的select框
 * @param tableArr
 * @returns {string}
 */
function generateVisualTableNameSelectEle(tableArr, readerOrWriter) {

    var firstTableName = tableArr[0];
    var tableNames = "";

    for (var index in tableArr) {
        tableNames += "" +
            "<li data-original-index='" + index + "' " +
            "class='selected " + readerOrWriter + "-tableName-li'>" +
            "<a tabindex='0' class='' style='' data-tokens='null'>" +
            "<span class='text'>" + tableArr[index] + "</span>" +
            "<span class='glyphicon glyphicon-ok check-mark'></span>" +
            "</a>" +
            "</li>";
    }

    var tableNameSelect = "" +
        "<div class='btn-group bootstrap-select open'> " +
        "<button id='" + readerOrWriter + "-visualTableSelect-title' " +
        "type='button' class='btn dropdown-toggle btn-default' style='width: 380px' " +
        "data-toggle='dropdown' " +
        "title=" + firstTableName + "aria-expanded='true'> " +
        "<span class='filter-option pull-left'>" +
        firstTableName +
        "</span>&nbsp; " +
        "<span class='caret'></span> " +
        "</button>" +
        "<div class='dropdown-menu open' " +
        "style='max-height: 690.365px; overflow: hidden; min-height: 92px;'> " +
        "<ul class='dropdown-menu inner' role='menu' " +
        "style='max-height: 690.365px; overflow-y: auto; min-height: 92px;'>" +
        tableNames +
        "</ul>" +
        "</div>" +
        "</div>";

    return tableNameSelect;
}

/**
 * 注册点击TableNameLi事件
 * @param readerOrWriter
 */
function registerClickTableNameLiEvent(readerOrWriter) {

    $(document).on("click", "." + readerOrWriter + "-tableName-li", function () {
        var tableName = $.trim($(this).find("span.text").html());

        var visualTableSelectTitle = $("#" + readerOrWriter + "-visualTableSelect-title");
        visualTableSelectTitle.attr("title", tableName);

        var titleSpan = visualTableSelectTitle.find("span.filter-option");
        titleSpan.empty();
        titleSpan.append(tableName);

        var tableSelect = $("#" + readerOrWriter + "-table-select");
        tableSelect.val(tableName);

        tableSelect.trigger("change");
    });
}

/**
 * 根据dataSource的id获取tableName的数组
 * @param id
 * @returns {Array}
 */
function getTableArrByDataSourceId(id) {
    var tableArr = [];
    var params = {};
    params['id'] = id;
    $.postHttpSync(params, getUrlBySuffix("/datasource/getTables"), function (json) {
        if (json && json.success) {
            tableArr = json['list'];
        }
    })
    return tableArr;
}

/**
 * 根据数据源，设置reader或者writer的Form
 * @param dataSource
 * @param formId
 */
function fillReaderOrWriterForm(dataSource, formId) {
    $.each($('#' + formId).parent().find(".form-control"), function () {
        var name = $(this).attr("name");
        if (isNull(name)) {
            return true;
        }
        if (name == "readerUsername" || name == "writerUsername") {
            var value = dataSource['userName'];
            $(this).val($.trim(value));
            return true;
        }
        if (name == "readerPassword" || name == "writerPassword") {
            var value = dataSource['password'];
            $(this).val($.trim(value));
            return true;
        }
        if (name == "readerJdbcUrl" || name == "readerJdbcUrls" || name == "writerJdbcUrl") {
            var value = dataSource['jdbcUrl'];
            $(this).val($.trim(value));
            return true;
        }
    });
}

/**
 * 根据readerType，判断是否显示dataSource选择区
 * @param readerType
 * @returns {boolean}
 */
function showReaderDataSourceSelect(readerType) {
    $("#reader-datasource-treeview").empty();
    if (isNull(readerType)) {
        return false;
    }
    readerType = $.trim(readerType);
    if (readerOrWriterTypeHasDataSource.indexOf(readerType) != -1) {
        showOneTypeDataSource("reader-datasource-treeview", readerType, readerDataSourceButtons);
        $("#reader-datasource-select-div").show();
        return true;
    } else {
        $("#reader-datasource-select-div").hide();
        return false;
    }
}

/**
 * 根据readerType选择是否显示readerTable的select框
 * @param readerType
 */
function showReaderTableSelect(readerType) {
    $("#reader-table-select-div").hide();
    var selectRow = $("#reader-table-select-row");
    selectRow.empty();
    if (readerOrWriterTypeHasDataSource.indexOf(readerType) != -1) {
        $("#reader-table-select-div").show();
        var warnInfo = "<span style='font-size: 17px;color: red;font-weight: 400'>请先选择数据源</span>";
        selectRow.append(warnInfo);
    }
}


/**
 *根据writerType选择是否显示writerTable的select框
 * @param writerType
 */
function showWriterTableSelect(writerType) {
    $("#writer-table-select-div").hide();
    var selectRow = $("#writer-table-select-row");
    selectRow.empty();
    if (readerOrWriterTypeHasDataSource.indexOf(writerType) != -1) {
        $("#writer-table-select-div").show();
        var warnInfo = "<span style='font-size: 17px;color: red;font-weight: 400'>请先选择数据源</span>";
        selectRow.append(warnInfo);
    }
}

/**
 * 根据writerType，判断是否显示dataSource选择区
 * @param writerType
 * @returns {boolean}
 */
function showWriterDataSourceSelect(writerType) {
    $("#writer-datasource-treeview").empty();
    if (isNull(writerType)) {
        return false;
    }
    writerType = $.trim(writerType);
    if (readerOrWriterTypeHasDataSource.indexOf(writerType) != -1) {
        showOneTypeDataSource("writer-datasource-treeview", writerType, writerDataSourceButtons);
        $("#writer-datasource-select-div").show();
        return true;
    } else {
        $("#writer-datasource-select-div").hide();
        return false;
    }
}